package com.hn.zhijian.system.config;

import com.hn.zhijian.base.common.ConfigurationYmlProperty;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author carl chen
 * @Classname ThreadPoolConfig
 * @Description TODO
 * @Date 2019/11/11 15:04
 */
@EnableAsync
@Configuration
public class ThreadPoolConfig {

    @Autowired
    private ConfigurationYmlProperty config;

    /**
     *  bean的名称，默认为首字母小写的方法名
     * @return
     */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor(){

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(config.getCorePoolSize());

        executor.setMaxPoolSize(config.getMaxPoolSize());

        executor.setQueueCapacity(config.getQueueCapacity());

        executor.setKeepAliveSeconds(config.getKeepAliveTime());

        executor.setThreadNamePrefix(config.getThreadNamePrefix());

        // 线程池对拒绝任务的处理策略
        // CallerRunsPolicy：由调用线程（提交任务的线程）处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();

        return executor;
    }

}
